package fastdht

import (
	"bytes"
	log "github.com/golang/glog"
	"github.com/nictuku/nettools"
	"github.com/zeebo/bencode"
	"net"
)

func encodeMsg(query interface{}) ([]byte, error) {
	var b bytes.Buffer
	encode := bencode.NewEncoder(&b)
	if err := encode.Encode(query); err != nil {
		log.V(1).Infoln("encode Msg is error")
		return nil, err
	}
	return b.Bytes(), nil
}

func decodeMsg(buff []byte) (result *reviceType, e error) {
	decode := bencode.NewDecoder(bytes.NewBuffer(buff))

	if err := decode.Decode(&result); err == nil {
		return
	}
	return
}
func parseNodesString(nodes string) (parsed map[string]*net.UDPAddr) {
	parsed = make(map[string]*net.UDPAddr)
	if len(nodes)%nodeContactLen > 0 {
		log.V(3).Infof("DHT: len(NodeString) = %d, INVALID LENGTH, should be a multiple of %d", len(nodes), nodeContactLen)
		log.V(5).Infof("%T %#v\n", nodes, nodes)
		return
	} else {
		log.V(2).Infof("DHT: len(NodeString) = %d, had %d nodes, nodeContactLen=%d\n", len(nodes), len(nodes)/nodeContactLen, nodeContactLen)
	}
	for i := 0; i < len(nodes); i += nodeContactLen {

		id := nodes[i : i+nodeIdLen]
		address := nettools.BinaryToDottedPort(nodes[i+nodeIdLen : i+nodeContactLen])
		taddress, e := net.ResolveUDPAddr("udp4", address)
		if e != nil {
			continue
		}
		parsed[id] = taddress
	}
	return
}
